package cn.lnl.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LNL
 * @date 2021/8/15 22:44
 */
@Component
public class MyLB implements LoadBalance {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    //做一步类似轮询算法同步骤的CAS操作
    public final int getAndIncrement() {
        int current;//当前的值
        int next;//下一个值
        do {
            //获取到当前的值
            current = this.atomicInteger.get();
            //判断next是否大于一个阈值，如果大于就进行重新开始从0计算
            next = current > 2147483647 ? 0 : current + 1;
        } while(!this.atomicInteger.compareAndSet(current,next));//如果预期的值和内存的值不一样，则在此处进行自旋
        System.out.println("***********next: " + next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {

        //获取到当前服务的下标
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
